package com.laicunba.event.listener;

import java.math.BigDecimal;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Map;

import org.apache.log4j.Logger;
import org.json.simple.JSONArray;
import org.json.simple.parser.JSONParser;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationListener;
import org.springframework.stereotype.Component;

import com.laicunba.event.PaySuccessEvent;
import com.laicunba.pojo.FinancingTargetBidDO;
import com.laicunba.pojo.RegistryDO;
import com.laicunba.service.RegistryService;
import com.laicunba.util.BigDecimalUtil;
import com.laicunba.util.DateUtil;

@Component
public class InvestCashBackListener implements ApplicationListener<PaySuccessEvent> {
	private static final Logger LOG = Logger.getLogger(InvestCashBackListener.class);

	@Autowired
	private RegistryService registryService;

	@SuppressWarnings("unchecked")
	@Override
	public void onApplicationEvent(PaySuccessEvent event) {
		try {
			FinancingTargetBidDO bidDO = (FinancingTargetBidDO) event.getSource();
			DateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
			RegistryDO onOffRegistry = registryService.get(RegistryDO.class, "act.invest-cash-back.open");
			if(bidDO != null && bidDO.getType().equalsIgnoreCase("CPB") && onOffRegistry != null) {
				JSONArray actTimeArray = (JSONArray)new JSONParser().parse(onOffRegistry.getVal());
				if(actTimeArray != null) {
					Map<String, String> tempMap = (Map<String, String>) actTimeArray.get(0);
					if(tempMap != null && new Date().compareTo(sdf.parse(tempMap.get("start_time"))) >= 1 && new Date().compareTo(sdf.parse(tempMap.get("end_time"))) < 1) {
						RegistryDO totalInvestAmountRegistry = null;
						int period = DateUtil.days(bidDO.getPayTime(), bidDO.getEndProfit());
						LOG.info(String.format("【投资返现活动】用户投资订单信息，订单id为[%s],userId=[%s],标的id为[%s],标的类型为[%s],购买金额为[%s],理财期限为[%s],payMark为[%s],下单时间为[%s]", bidDO.getId(), bidDO.getBidUserId(), bidDO.getFinancingTargetId(), bidDO.getType(), bidDO.getBuyAmount(), period, bidDO.getPayMark(), bidDO.getPayTime()));
						if(period >= 30 && period < 50) {
							period = 30;
						} else if(period >= 50 && period < 80) {
							period = 60;
						} else if(period >= 80) {
							period = 90;
						}
						totalInvestAmountRegistry = registryService.get(RegistryDO.class, "u." + bidDO.getBidUserId() + ".invest-cash-back.amount" + period);
						if(totalInvestAmountRegistry != null) {
							LOG.info(String.format("【投资返现活动】即将增加累计投资金额，注册表id为[%s],增加前累计投资金额为[%s],即将增加累计投资金额[%s],增加后累计投资金额应为[%s]", "u." + bidDO.getBidUserId() + ".invest-cash-back.amount" + period, totalInvestAmountRegistry.getVal(), bidDO.getBuyAmount(), BigDecimalUtil.format(new BigDecimal(totalInvestAmountRegistry.getVal()).add(bidDO.getBuyAmount()))));
							totalInvestAmountRegistry.setVal(BigDecimalUtil.format(new BigDecimal(totalInvestAmountRegistry.getVal()).add(bidDO.getBuyAmount())));
							registryService.updateSkipCheckOwner(totalInvestAmountRegistry);
						} else {
							LOG.info(String.format("【投资返现活动】即将新增累计投资金额，注册表id为[%s],增加前累计投资金额为[%s],即将增加累计投资金额[%s],增加后累计投资金额应为[%s]", "u." + bidDO.getBidUserId() + ".invest-cash-back.amount" + period, 0, bidDO.getBuyAmount(), BigDecimalUtil.format(bidDO.getBuyAmount())));
							totalInvestAmountRegistry = new RegistryDO();
							totalInvestAmountRegistry.setId("u." + bidDO.getBidUserId() + ".invest-cash-back.amount" + period);
							totalInvestAmountRegistry.setVal(BigDecimalUtil.format(bidDO.getBuyAmount()));
							totalInvestAmountRegistry.setVisible(true);
							registryService.create(totalInvestAmountRegistry);
						}
					}
				}
			}
		} catch (Exception e) {
			LOG.error("【投资返现活动】增加累计投资金额异常", e);
		}
	}
	
}
